package servlets;

import hibernatelogic.HibTransactions;

import java.io.IOException;
import java.sql.SQLException;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Transactions;

@WebServlet("/make-transaction-servlet")
public class MakeTransactionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger loggerMakeTransactionsServlet = Logger.getLogger(MakeTransactionServlet.class);
       
    public MakeTransactionServlet() {
        super();
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession sess = request.getSession();
		
		//Are you really user?
		if(((String) sess.getAttribute("UserRole")).equals("1")) {
			
			HibTransactions hibTransactions = new HibTransactions();
			Transactions transaction = new Transactions();
			GregorianCalendar gc = new GregorianCalendar();
			
			//Requesting parameters
			int userid = Integer.parseInt((String) sess.getAttribute("UserID"));
			int itemid = Integer.parseInt(request.getParameter("ntransaction"));
			int quantity = Integer.parseInt(request.getParameter("nquantity"));
			
			//Creating new transaction
			transaction.setItems(itemid);
			transaction.setQuantity(quantity);
			transaction.setUsers(userid);
			transaction.setSal_time(gc);
			transaction.setStatus("N");
			
			try {
				//Trying to add new transaction
				hibTransactions.addTransaction(transaction);
			} catch (SQLException e) {
				loggerMakeTransactionsServlet.error("Something wrong with MakeTransactionsServlet", e);
			} finally {
				//Destroy and redirect
				hibTransactions = null;
				transaction = null;
				gc = null;
				response.sendRedirect("/my-pet-project-0/UMakeTransactions.jsp");
			}
		} else {
			response.sendError(response.SC_FORBIDDEN);
		}
	}
}
